﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CinemaWS.Model;
using CinemaWS.Model.CustomEntities;
using Libs;
namespace CinemaWS.Repository
{
    public static class CinemaRepository
    {
        private static CinemaServiceEntities dataEntities = new CinemaServiceEntities();

        public static CinemaEntity ConvertToEntity(Cinema cinema)
        {
            return new CinemaEntity
                    {
                        ID = cinema.ID,
                        Name = cinema.Name,
                        Tel = cinema.Tel,
                        Address = cinema.Address,
                        Website = cinema.Website,
                        ImageUrl = cinema.ImageUrl,
                        GroupName = cinema.GroupName,
                        Description = cinema.Description,
                        City = cinema.City,
                        Fax = cinema.Fax,
                        Email = cinema.Email
                    };
        }

        public static CinemaEntity[] ConvertToArray(List<Cinema> list)
        {
            CinemaEntity[] cinemaList = new CinemaEntity[list.Count()];
            for (int i = 0; i < list.Count(); i++)
            {
                Add(i, cinemaList, ConvertToEntity(list[i]));
            }
            return cinemaList;
        }

        /// <summary>
        /// Insert object to array
        /// </summary>
        /// <param name="index">index</param>
        /// <param name="list">list of objects</param>
        /// <param name="cinema">object for inserting</param>
        private static void Add(int index,CinemaEntity[] list,CinemaEntity cinema)
        {
            list[index++] = cinema;
        }

        public static CinemaEntity[] GetAll()
        {
            try
            {
                var list = dataEntities.Cinema.ToList();
                return ConvertToArray(list);
            }
            catch
            {
                return null;
            }
        }

        public static CinemaEntity[] GetCinemasByCity(string city)
        {
            try
            {
                var list = dataEntities.Cinema.Where(cinema => cinema.City.Contains(city)).ToList();
                return ConvertToArray(list);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// Get a cinema by ID
        /// </summary>
        /// <param name="cinemaID">cinema ID</param>
        /// <returns></returns>
        public static CinemaEntity GetDetail(int cinemaID)
        {
            try
            {
                var c = dataEntities.Cinema.First(cn => cn.ID == cinemaID);
                return ConvertToEntity(c);
            }
            catch
            {
                return null;
            }
        }
    }
}
